<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.name')" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input :placeholder="$t('table.contact_no')" v-model="listQuery.tel" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input :placeholder="$t('table.address')" v-model="listQuery.address" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.type" class="filter-item" placeholder="Please select" clearable multiple>
        <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.category" class="filter-item" placeholder="Please select" clearable multiple>
        <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.available" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in availableOptions" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%;">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column :label="$t('table.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.type')" min-width="50px">
        <template slot-scope="scope">
          <span>{{ scope.row.type == 0 ? 'Home Delivery' : (scope.row.type == 1 ? 'Nood Food' : 'Pura Yoga') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.name')" min-width="120px">
        <template slot-scope="scope">
          <span>{{ scope.row.curname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.contact_no')" min-width="50px">
        <template slot-scope="scope">
          <span>{{ scope.row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.address')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.curaddress }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.bussiness_hours')" min-width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.curbussiness_hours }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.available')" class-name="status-col" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_available | availableFilter">{{ scope.row.available_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.created_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updated_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="deleteData(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="950px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="margin-left:50px;">
        <el-form-item :label="$t('table.area')">
          <el-select v-model="temp.area" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, index) in areaOptions" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.available')">
          <el-radio v-model="temp.is_available" label="1" name="is_avaliable">{{ $t('table_element.available.on') }}</el-radio>
          <el-radio v-model="temp.is_available" label="0" name="is_avaliable">{{ $t('table_element.available.un') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('table.type')">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('table.category')">
          <el-select v-model="temp.category" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('table.tel')">
          <el-input v-model="temp.tel" name="tel" />
        </el-form-item>

        <!-- <el-form-item :label="$t('table.freight')">
          <el-input v-model="temp.freight" name="freight" />
        </el-form-item> -->

        <el-form-item :label="$t('table.google_latlon')">
          <el-input v-model="temp.latitude" name="latitude" style="width:100px" /> <el-input v-model="temp.longitude" name="longitude" style="width:100px" />
        </el-form-item>
        <el-form-item :label="$t('table.baidu_latlon')">
          <el-input v-model="temp.latitude2" name="latitude2" style="width:100px" /> <el-input v-model="temp.longitude2" name="longitude2" style="width:100px" />
        </el-form-item>

        <el-form-item label="Location Search">
          <el-input v-model="locationinput">
            <el-button id="locationsearch" slot="append" icon="el-icon-search" name="locationseach" @click="locationseach"/>
          </el-input>
        </el-form-item>
        <template>
          <el-tabs v-model="activeMap">
            <el-tab-pane label="googleMap" name="googleMap">
              <el-input v-model="temp.maptype" name="maptype" type="hidden"/>
              <GmapMap
                      ref="googleMapRef"
                      :center="{lat:22.543696, lng:114.0621675}"
                      :zoom="zoom"
                      map-type-id="terrain"
                      class="bm-view"
                      @click="googlemapclick"
              >
                <GmapMarker
                        :position="{lng: googleCenter.lng, lat: googleCenter.lat}"
                        :clickable="true"
                        :draggable="true"
                />
              </GmapMap>
            </el-tab-pane>
            <el-tab-pane label="baiduMap" name="baiduMap" >
              <template>
                <el-input v-model="temp.maptype" name="maptype" type="hidden"/>
                <baidu-map :center="center" :zoom="zoom" ak="P6SZd8lG3amDOpH9niP01rliV8nhvSiQ" class="bm-view" @ready="handlerMap" @click="getClickInfo">
                  <bm-geolocation :show-address-bar="true" :auto-location="true" anchor="BMAP_ANCHOR_BOTTOM_RIGHT"/>
                  <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"/>
                  <bm-marker :position="{lng: center.lng, lat: center.lat}" :dragging="true" animation="BMAP_ANIMATION_BOUNCE"/>
                </baidu-map>
              </template>
            </el-tab-pane>
          </el-tabs>
        </template>

        <template>
          <el-tabs v-model="activeName" >
            <el-tab-pane label="en" name="first">
              <el-form-item :label="$t('table.name')" required prop="name">
                <el-input v-model="temp.name" name="name" />
              </el-form-item>
              <el-form-item :label="$t('table.address')" required prop="address">
                <el-input v-model="temp.address" name="address"/>
              </el-form-item>
              <el-form-item :label="$t('table.bussiness_hours')">
                <el-input v-model="temp.bussiness_hours" name="bussiness_hours"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-cn" name="second">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.cnname" name="cnname" />
              </el-form-item>
              <el-form-item :label="$t('table.address')">
                <el-input v-model="temp.cnaddress" name="cnaddress"/>
              </el-form-item>
              <el-form-item :label="$t('table.bussiness_hours')">
                <el-input v-model="temp.cnbussiness_hours" name="cnbussiness_hours"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-hk" name="third">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.hkname" name="hkname" />
              </el-form-item>
              <el-form-item :label="$t('table.address')">
                <el-input v-model="temp.hkaddress" name="hkaddress"/>
              </el-form-item>
              <el-form-item :label="$t('table.bussiness_hours')">
                <el-input v-model="temp.hkbussiness_hours" name="hkbussiness_hours"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-tw" name="fourth">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.twname" name="twname" />
              </el-form-item>
              <el-form-item :label="$t('table.address')">
                <el-input v-model="temp.twaddress" name="twaddress"/>
              </el-form-item>
              <el-form-item :label="$t('table.bussiness_hours')">
                <el-input v-model="temp.twbussiness_hours" name="twbussiness_hours"/>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchShow, fetchStore, fetchUpdate, fetchDelete, fetchBatchDelete, fetchGoogleGeometry } from '@/api/location'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import i18n from '@/lang/index'
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import bmGeolocation from 'vue-baidu-map/components/controls/Geolocation.vue'
import bmNavigation from 'vue-baidu-map/components/controls/Navigation.vue'
import bmMarker from 'vue-baidu-map/components/overlays/Marker.vue'
import Vue from 'vue'
import * as VueGoogleMaps from 'vue2-google-maps'

import VueJsonp from 'vue-jsonp'

Vue.use(VueGoogleMaps, {
  load: {
    key: 'AIzaSyBn_GL_uRs9KdySX8pii0GMGy9JwFFQpk0',
    libraries: 'places'
  }
})

Vue.use(VueJsonp)

export default {
  name: 'Location',
  components: { Pagination, Tinymce, BaiduMap, bmGeolocation, bmNavigation, bmMarker, VueJsonp },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    }
  },
  load: {
    key: 'AIzaSyBn_GL_uRs9KdySX8pii0GMGy9JwFFQpk0',
    libraries: 'places'
  },
  data() {
    return {
      // gggglobe: this.$store.state.locale.global, // store例子
      activeName: 'first',
      activeMap: 'googleMap',
      isAvailable: 2,
      tableKey: 0,
      list: null,
      content: ``,
      total: 0,
      listLoading: true,
      listQuery: {
        area: this.$store.getters.area,
        page: 1,
        limit: 20,
        available: 2,
        name: '',
        tel: '',
        address: '',
        type: [],
        category: [],
        lang: i18n.locale
      },
      location_ids: [],
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, { 'value': 0, 'name': i18n.t('table_element.available.un') }],
      // areaOptions: [{ name : '中国香港', id: 1 }, { name : '中国大陆', id: 2 }],
      typeList: [{ name: 'Home Delivery', id: 0 }, { name: 'nood food', id: 1 }, { name: 'Pura Yoga', id: 2 }],
      categoryList: [],
      showReviewer: false,
      temp: {
        id: '',
        is_available: '1',
        activeMap: 'googleMap',
        category: '',
        type: 0,
        area: 96,
        latitude: 0,
        longitude: 0,
        latitude2: 0,
        longitude2: 0,
        maptype: 1,
        freight: 0,
        name: '',
        address: '',
        bussiness_hours: '',
        cnname: '',
        cnaddress: '',
        cnbussiness_hours: '',
        hkname: '',
        hkaddress: '',
        hkbussiness_hours: '',
        twname: '',
        twaddress: '',
        twbussiness_hours: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      center: { lng: 114.067632, lat: 22.540279 },
      zoom: 15,
      googleCenter: { lng: 114.0621675, lat: 22.543696 },
      markers: [{
        position: { lng: 114.0621675, lat: 22.543696 }
      }],
      locationinput: ''
    }
  },
  computed: {
    areaOptions: function() {
      return this.$store.state.locale.areas
    }
  },
  created() {
    this.getList()
  },

  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        // console.log(response)
        var data = response.data
        this.list = data.data.data
        this.total = data.data.total
        this.categoryList = data.data.categoryList

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Successful operation',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        is_available: '1',
        activeMap: 'googleMap',
        category: '',
        type: 0,
        area: 96,
        latitude: 0,
        longitude: 0,
        latitude2: 0,
        longitude2: 0,
        maptype: 1,
        freight: 0,
        name: '',
        address: '',
        bussiness_hours: '',
        cnname: '',
        cnaddress: '',
        cnbussiness_hours: '',
        hkname: '',
        hkaddress: '',
        hkbussiness_hours: '',
        twname: '',
        twaddress: '',
        twbussiness_hours: '',
      }
    },
    handleCreate() {
      // store例子
      // let ll = ['cc', 'aa']
      // this.$store.dispatch('addLocale', ll)
      // this.gggglobe = this.$store.state.locale.global
      // console.log('global1', this.gggglobe)
      // store例子end
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        // window.tinymce.get('fContent').setContent('')
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp.lang = i18n.locale
          fetchStore(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.is_available = this.temp.is_available.toString()
      this.temp.category = this.temp.category < 1 ? '' : parseInt(this.temp.category)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (this.temp.maptype === 1) {
        this.activeMap = 'googleMap'
      } else {
        this.activeMap = 'baiduMap'
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        // window.tinymce.get('fContent').setContent(this.temp.content)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lang = i18n.locale
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      console.log(row)
      this.$notify({
        title: 'Success',
        message: 'Delete Success!',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    deleteData(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchBatchDelete({ location_id: this.location_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.location_ids.indexOf(element.id) == -1) {
          this.location_ids.push(element.id)
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handlerMap({ BMap, map }) {
      console.log(BMap, map)
      this.center.lng = 114.067632
      this.center.lat = 22.540279
    },

    getClickInfo(e) {
      this.temp.maptype = 1
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat
      this.temp.longitude2 = e.point.lng
      this.temp.latitude2 = e.point.lat
    },
    googlemapclick(e) {
      console.log(e)
      this.temp.maptype = 2
      this.googleCenter.lng = e.latLng.lng()
      this.googleCenter.lat = e.latLng.lat()
      this.temp.longitude = e.latLng.lng()
      this.temp.latitude = e.latLng.lat()
      this.setGoogleMapCenter(e.latLng.lat(), e.latLng.lng())
    },

    setGoogleMapCenter(lat, lng) {
      this.$refs.googleMapRef.$mapPromise.then((map) => {
        map.panTo({lat: lat, lng: lng})
      })
    },

    locationseach() {
      if (this.locationinput !== '') {
        if (this.activeMap === 'baiduMap') {
          this.$jsonp('http://api.map.baidu.com/geocoder/v2/?address=' + this.locationinput + '&output=json&ak=P6SZd8lG3amDOpH9niP01rliV8nhvSiQ&type=jsonp&callback=showlocation').then(response => {
            // 返回数据 json， 返回的数据就是json格式
            if (response.status === 0) {
              this.center.lng = response.result.location.lng
              this.center.lat = response.result.location.lat
              this.temp.longitude2 = response.result.location.lng
              this.temp.latitude2 = response.result.location.lat
            }
          }).catch(err => {
            console.log(err)
          })
        }

        if (this.activeMap === 'googleMap') {
//            console.log('I am here');
          fetchGoogleGeometry({ 'address': this.locationinput }).then((response) => {
            var data = response.data
            console.log(data);
            if (data.code == 0) {
              this.googleCenter.lng = data.data.lng
              this.googleCenter.lat = data.data.lat
              this.temp.longitude = data.data.lng
              this.temp.latitude = data.data.lat
              this.setGoogleMapCenter(data.data.lat, data.data.lng)
            }
          })
          // this.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURI(this.locationinput) + '&key=AIzaSyBn_GL_uRs9KdySX8pii0GMGy9JwFFQpk0&type=jsonp&callback=showlocation').then(response => {
          //   // 返回数据 json， 返回的数据就是json格式
          //   if (response.code === 0) {
          //     this.googleCenter.lng = response.result.geometry.location.lng
          //     this.googleCenter.lat = response.result.geometry.location.lat
          //     this.temp.longitude = response.result.geometry.location.lng
          //     this.temp.latitude = response.result.geometry.location.lat
          //     console.log(this.temp.maptype)
          //   }
          // }).catch(err => {
          //   console.log(err)
          // })
        }
      }
    }
  }
}
</script>
<style>
  .bm-view {
    width: 100%;
    height: 300px;
  }
</style>
